package com.woniu.service.impl;

import com.woniu.dao.ProductDao;
import com.woniu.entity.Product;
import com.woniu.entity.utils.ResponseEntity;
import com.woniu.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    ProductDao productDao;

    @Override
    public Product addOne(Product product) {
        return  productDao.save(product);
    }

    @Override
    public ResponseEntity findOneById(Integer pid) {
        Optional<Product> byId = productDao.findById(pid);

        //判断byId是否存在，存在就返回数据；不存在就返回错误信息
        if(byId.isPresent()){
            return new ResponseEntity(byId.get());
        }else {
            return ResponseEntity.ERROR;
        }

    }

    @Override
    public ResponseEntity updateProduct(Product product) {
        return new ResponseEntity(productDao.save(product));
    }

    @Override
    public ResponseEntity findAllByNameOrPrice(String name, double minPrice, double maxPrice) {
        List<Product> products = productDao.findByNameOrPriceBetween(name,minPrice,maxPrice);
        return new ResponseEntity(products);
    }
}
